import React, { useContext, useEffect, useRef, useState } from "react";
import {
  Button,
  Form,
  Input,
  Popconfirm,
  Table,
  DatePicker,
  Select,
} from "antd";
import * as XLSX from "xlsx"; // 引入excel组件，用于导出
import { useLocation } from "react-router-dom";

const { Option } = Select;
const { RangePicker } = DatePicker;
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

const SysLog = () => {
  const [dataSource, setDataSource] = useState([]);
  const [filteredDataSource, setFilteredDataSource] = useState([]);
  const [count, setCount] = useState(0);
  const [userFilter, setUserFilter] = useState(null);
  const [timeFilter, setTimeFilter] = useState(null);
  const location = useLocation();
  const role = location.state?.role || "logger";

  useEffect(() => {
    // 读取 localStorage 中的登入和登出信息
    const loginRecords =
      JSON.parse(window.localStorage.getItem("loginRecords")) || [];
    const logoutRecords =
      JSON.parse(window.localStorage.getItem("logoutRecords")) || [];

    const logs = [];
    loginRecords.forEach((loginRecord, index) => {
      const logoutRecord = logoutRecords.find(
        (record) =>
          record.loginTime === loginRecord.time &&
          record.user === loginRecord.user
      );
      // 遍历本地存储的记录并添加到列表对应列中
      logs.push({
        key: count + index,
        name: loginRecord.user,
        loginTime: loginRecord.time,
        logoutTime: logoutRecord ? logoutRecord.logoutTime : "未退出",
      });
      setCount((prevCount) => prevCount + 1);
    });

    setDataSource(logs);
    setFilteredDataSource(logs);
  }, []);

  const handleDelete = (key) => {
    const newData = filteredDataSource.filter((item) => item.key !== key);
    setFilteredDataSource(newData);
  };

  const defaultColumns = [
    {
      title: "用户名",
      dataIndex: "name",
      width: "30%",
      editable: true,
      filters: dataSource.map((item) => ({
        text: item.name,
        value: item.name,
      })),
      onFilter: (value, record) => record.name === value,
    },
    {
      title: "登入时间",
      dataIndex: "loginTime",
      filters: dataSource.map((item) => ({
        text: item.loginTime,
        value: item.loginTime,
      })),
      onFilter: (value, record) => record.loginTime === value,
    },
    {
      title: "退出时间",
      dataIndex: "logoutTime",
    },
    // {
    //   title: "操作",
    //   dataIndex: "operation",
    //   render: (_, record) =>
    //     filteredDataSource.length >= 1 ? (
    //       <>
    //         <Popconfirm
    //           title="确定删除吗?"
    //           onConfirm={() => handleDelete(record.key)}
    //         >
    //           <a>删除</a>
    //         </Popconfirm>
    //         &emsp;
    //         <span>
    //           <a>查看</a>
    //         </span>
    //       </>
    //     ) : null,
    // },
  ];

  if (role === "admin" || role === "maintainer") {
    defaultColumns.push({
      title: "操作",
      dataIndex: "",
      key: "x",
      render: (_, record) =>
        filteredDataSource.length >= 1 ? (
          <>
            <Popconfirm
              title="确定删除吗?"
              onConfirm={() => handleDelete(record.key)}
            >
              <a>删除</a>
            </Popconfirm>
            &emsp;
            <span>
              <a>查看</a>
            </span>
          </>
        ) : null,
    });
  }

  const handleSave = (row) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  const handleUserFilterChange = (value) => {
    setUserFilter(value);
    filterData(value, timeFilter);
  };

  const handleTimeFilterChange = (dates, dateStrings) => {
    setTimeFilter(dateStrings);
    filterData(userFilter, dateStrings);
  };

  const filterData = (user, time) => {
    let filteredData = dataSource;

    if (user) {
      filteredData = filteredData.filter((item) => item.name === user);
    }

    if (time && time.length === 2) {
      filteredData = filteredData.filter(
        (item) =>
          new Date(item.loginTime) >= new Date(time[0]) &&
          new Date(item.loginTime) <= new Date(time[1])
      );
    }

    setFilteredDataSource(filteredData);
  };

  const exportToExcel = () => {
    // 将数据转换为工作表格式
    const worksheet = XLSX.utils.json_to_sheet(dataSource);
    // 创建一个新的工作簿
    const workbook = XLSX.utils.book_new();
    // 将工作表添加到工作簿中
    XLSX.utils.book_append_sheet(workbook, worksheet, "SysLog");
    // 将工作簿保存为一个 Excel 文件并下载
    XLSX.writeFile(workbook, "SysLog.xlsx"); // 导出文件名
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  return (
    <div>
      <Button
        type="primary"
        size="small"
        style={{ position: "absolute", top: "159px", left: "240px" }}
        onClick={exportToExcel}
      >
        导出日志
      </Button>
      <RangePicker
        onChange={handleTimeFilterChange}
        style={{ marginTop: "35px" }}
      />
      <Select
        style={{ width: 120, marginLeft: 10 }}
        placeholder="Select a user"
        allowClear
        onChange={handleUserFilterChange}
      >
        {dataSource.map((user) => (
          <Option key={user.name} value={user.name}>
            {user.name}
          </Option>
        ))}
      </Select>
      <Table
        components={components}
        rowClassName={() => "editable-row"}
        bordered
        dataSource={filteredDataSource}
        columns={columns}
        style={{ marginTop: "16px" }}
      />
    </div>
  );
};

export default SysLog;
